package com.alvin.demo;

import org.apache.catalina.Server;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.startup.Tomcat;

import java.net.URLDecoder;

public class StartServer {

	public static void main(String[] args) {

		if (args.length < 2 ) {
			System.out.println("未配置项目路径，不能启动！！");
			return ;
		}
		String server_path = args[0];
		String server_name = "";
		int port = 8080;

		String[] params = args[1].split("::");
		if (params.length >= 1) {
			server_name = params[0];
		}
		if (params.length >= 2) {
			port = Integer.parseInt(params[1]);
		}

		// 防止路径中文乱码
		try {
			server_path = URLDecoder.decode(server_path, "UTF-8");
		} catch (Exception exception) {
			exception.printStackTrace();
		}
		Tomcat tomcat = new Tomcat();
		// 项目当前目录
		tomcat.setBaseDir(server_path);
		tomcat.getHost().setAppBase(server_path);
		// 设置Tomcat上下文, 加载webapp下的所有文件信息, 包括web.xml
		// addWebapp 方法具有读取信息自动装配的功能（目录结构必须符合规范），自动生成web应用
		tomcat.addWebapp("/" + server_name, server_path);
		Server server = tomcat.getServer();
		Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
		// 设置端口
		connector.setPort(port);
//        connector.setURIEncoding("UTF-8");
		connector.setThrowOnFailure(true);
		tomcat.getService().addConnector(connector);
		tomcat.setConnector(connector);
		try {
			tomcat.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
		server.await();
	}

}